package com.shb.game;

import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public abstract class Slide implements OnTouchListener {
	class PressLongClick implements Runnable {

		@Override
		public void run() {
			longclick();
		}

	}

	private final Handler handle;
	private final PressLongClick plc;
	int x1, y1, x2, y2;

	public static final int left = 1;
	public static final int right = 1 << 1;
	public static final int up = 1 << 2;
	public static final int down = 1 << 3;
	private final int SPACE = 30;

	private final int LONG_TIME = 500;
	private boolean isLongClick = false;
	private boolean isClick = false;
	private final int LONG_SPACE = 100;

	public Slide() {
		handle = new Handler();
		plc = new PressLongClick();
	}

	private void longclick() {
		isClick = false;
		isLongClick = false;
		onLongClick();
	}

	public abstract void onLongClick();

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			x1 = (int) event.getX();
			y1 = (int) event.getY();
			handle.postDelayed(plc, LONG_TIME);
			isLongClick = true;
			isClick = true;
			break;
		case MotionEvent.ACTION_MOVE:
			x2 = (int) event.getX();
			y2 = (int) event.getY();
			if (Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2) > LONG_SPACE) {
				handle.removeCallbacks(plc);
				isLongClick = false;
			}
			break;
		case MotionEvent.ACTION_UP:
			x2 = (int) event.getX();
			y2 = (int) event.getY();
			boolean b1 = x2 - x1 > SPACE;
			boolean b2 = x2 - x1 < -1 * SPACE;
			boolean b3 = y2 - y1 > SPACE;
			boolean b4 = y2 - y1 < -1 * SPACE;
			int result = 0;
			if (b1) {
				result |= right;
			}
			if (b2) {
				result |= left;
			}
			if (b3) {
				result |= up;
			}
			if (b4) {
				result |= down;
			}
			if (isLongClick) {
				handle.removeCallbacks(plc);
				isLongClick = false;
			}
			if (isClick) {
				slide(result);
			}
		}
		return true;
	}

	public abstract void slide(int s);

}
